<extend name="Public/base"/>

<block name="style">
    <style>
        .nav .nav-tabs{
            margin-top: 25px
        }
        #documentBox{width: 50%}
        #diyBox{width: 68%}
        #previewBox{position:fixed;right:10px;bottom:50px;width: 300px}
        #ArticlePreviewBox{width: 100%;min-height: 80px;border: 1px solid #eee; padding: 10px}
        .firstArticle{}
        .otherArticle{margin-top:5px;padding: 5px;border-top: 1px solid #ddd}
        .coverImage {height:9em;overflow:hidden}
        .coverImage img{ width:100%;}
        .firstTitle{bottom:0;right:0;left:0;height: 3em;background:rgba(0,0,0,0.6)!important;font-size: 1em;color:#fff}
        .firstTitle span {line-height: 1em}
        .itemTitle {width: 79%}
        .indexImage {width: 19%}
        .indexImage img {width: 100%}

    </style>
</block>

<block name="body">
    <div class="cf">
        <h2>{$meta_title}</h2>
    </div>
<div class="cf" id="create_button_box" >
        <ul class="nav nav-tabs">
            <li class="active" id="createFromDocument">
                <a href="#">系统文章</a>
            </li>
            <li id="createDiy"><a href="#">自定义输入</a></li>
        </ul>
</div>
    <div class="cf" id="editArea">
        <!-- 通过文章选择增加素材图文 -->
        <div class="fl createBox" id="documentBox">
            <div class="input-append">
                <input class="span2" id="docId" type="text" placeholder="输入文章编号">
                <button class="btn" type="button" id="addDocument">增加</button>
            </div>

            <div class="accordion"  id="documentsList">
                <div>历史增加文章列表：</div>

            </div>

            <div>

                <ol style="list-style: decimal">

                </ol>
            </div>
        </div>

        <!-- 自定义图文 -->
        <div class="fl row createBox" id="diyBox">
            <div class="editBox span7">
            <script type="text/javascript" src="__STATIC__/uploadify/jquery.uploadify.min.js"></script>
                <div class="controls">
                    <lable>标题：</lable>
                    <input type="text" class="text input-large" name="newsTitle" placeholder="输入标题">
                </div>

                <div class="controls">
                    <lable>封面图片：</lable>
                    <input type="file" id="upload_picture_cover">
                    <input type="hidden" name="newsCover" id="cover_id"/>
                    <div class="upload-img-box">
                    </div>
                </div>
                <script type="text/javascript">
                    //上传图片
                    /* 初始化上传插件 */
                    $("#upload_picture_cover").uploadify({
                        "height"          : 30,
                        "swf"             : "__STATIC__/uploadify/uploadify.swf",
                        "fileObjName"     : "download",
                        "buttonText"      : "上传图片",
                        "uploader"        : "{:U('File/uploadPicture',array('session_id'=>session_id()))}",
                        "width"           : 120,
                        'removeTimeout'	  : 1,
                        'fileTypeExts'	  : '*.jpg; *.png;',
                        'fileSizeLimit' :'64KB',
                        "onUploadSuccess" : uploadPictureCover,
                    'onFallback' : function() {
                        alert('未检测到兼容版本的Flash.');
                    }
                    });
                    function uploadPictureCover(file, data){
                        var data = $.parseJSON(data);
                        var src = '';
                        if(data.status){
                            $("#cover_id").val(data.id);
                            src = data.url || '__ROOT__' + data.path
                            $("#cover_id").parent().find('.upload-img-box').html(
                                    '<div class="upload-pre-item"><img src="' + src + '"/></div>'
                            );
                        } else {
                            updateAlert(data.info);
                            setTimeout(function(){
                                $('#top-alert').find('button').click();
                                $(that).removeClass('disabled').prop('disabled',false);
                            },1500);
                        }
                    }
                </script>

                <div class="controls">
                <label class="textarea">
                    <textarea id="newsContent" name="newsContent"></textarea>
                    {:hook('adminArticleEdit', array('name'=>'newsContent','value'=>''))}
                </label>
                </div>
                <div class="controls">
                    <label class="textarea">文章描述：
                        <textarea name="newsDescription"></textarea>
                    </label>
                </div>
                <div class="controls">
                    <lable>原文地址：</lable>
                    <input type="text" class="text input-large" name="newsUrl" placeholder="阅读原文的链接">
                </div>
                <div class="controls">
                    <a id="addDiyArticle" class="btn btn-default" href="javascript:">添加</a>
                </div>
            </div>

        </div>

        <!-- 预览区 -->
        <div class="fr" id="previewBox">
            <div id="ArticlePreviewBox">

            </div>
            <div class="submitBox">
                <input type="hidden" name="media_id" value=""/>
                <a class="btn btn-primary" id="saveLocal" href="javascript:">本地保存</a>
                <a class="btn btn-danger" id="saveAndUpload" href="javascript:">保存并上传到微信</a>
            </div>
        </div>
    </div>
    <div id="response">

    </div>
</block>

<block name="script">
    <script type="text/javascript" src="__STATIC__/Sortable.min.js"></script>

    <script type="text/javascript">

        //隐藏操作区域
        $("#diyBox").hide();
        //标签切换选择文章导入时
        $("#createFromDocument").click(function(){
            $(this).addClass("active").siblings().removeClass("active");
            $(".createBox").hide();
            $("#documentBox").fadeIn();
        });
        //标签切换选择自定义输入时
        $("#createDiy").click(function(){
            $(this).addClass("active").siblings().removeClass("active");
            $(".createBox").hide();
            $("#diyBox").fadeIn();
        });

        var countNum = $("#ArticlePreviewBox").find("div.localArticle").length;

        //提交文章编号时
        $("#addDocument").click(function(){

            if(countNum < 10){
                var doc_id = $("#docId").val();

                if($("#document"+doc_id).length>0){
                    showInfo('该文章已经添加');
                    exit();
                }
                $.post("{:U('findDocument')}",
                        {docId:doc_id},
                        function(data){
                            if(data.status == 0){
                                showInfo(data.info);
                            }else{
                                $(".accordion-body").removeClass("in");
                                var str = "<div class='accordion-group'>";
                                str += "<button class='close fixed' onclick='delArticle(this,true)' style='float:right;margin-top: 4px;'>&times;</button>"
                                str += "<div class='accordion-heading'>"
                                str += "<a class='accordion-toggle' data-toggle='collapse' data-parent='#articlesList' href='#collapse"+data.info.id+countNum+"'>";
                                str += data.info.title;
                                str += "</a>";
                                str += "</div>";
                                str += "<div id='collapse"+data.info.id+data.info.name+"' class='accordion-body collapse in'>";
                                str += "<div class='accordion-inner'>";
                                str += data.info.description;
                                str += "</div></div></div>";
                                $("#documentsList").append(str);
                                addPreviewItem(data);
                            }
                        }
                );
            }else{
                showInfo('最多只能添加10篇');
            }
        });

        //添加自定义图文时
        $("#addDiyArticle").click(function(){

            var title = $("input[name='newsTitle']").val();
            if(title == ''){showInfo('标题不能为空');exit()};

            var cover_id = $("input[name='newsCover']").val();
            if(!cover_id){showInfo('请上传封面图片');exit()};

            var description = $("textarea[name='newsDescription']").val();

            var content = editor_newsContent.html();

            var url = $("input[name='newUrl']").val();

            var data = {info:{"title":title,"cover_id":cover_id,"description":description,"content":content,"url":url}};

            $.post("{:U('addTchatArticle')}",
                    data,
                    function(re){
                        if(re.status == 0){
                            showInfo(re.info)
                        }else{
                            addPreviewItem(re.data);
                        }
                    }
            );
        });


        function saveData(data){
            var oldData = $('#ArticlePreviewBox').data('data');
            if(null == oldData){
                var newData = [{ id:''+data.info.itemType+data.info.article_id}];
            }else{
                var newData = oldData.concat([{ id:''+data.info.itemType+data.info.article_id }]);
            }

            $('#ArticlePreviewBox').data('data', newData);
        }

        //预览区添加预览条目
        function addPreviewItem(data){

                if(countNum >= 10){
                    showInfo("最多只能添加10篇");
                }else {
                    if (countNum == 0) {
                        var article = "<div id='"+data.info.itemType+data.info.article_id+"' class='firstArticle localArticle'>";
                        article += "<button class='close fixed' onclick='delArticle(this)' style='float:right;right:15px;margin-top: 4px;'>&times;</button>";
                        article += "<div class = 'coverImage'><img src='" + data.info.cover + "' /> </div>";
                        article += "<div class = 'firstTitle'><span>" + data.info.title + "</span></div>";
                        article += "</div>"
                    } else {
                        var article = "<div id='"+data.info.itemType+data.info.article_id+"' class='cf otherArticle localArticle'>";
                        article += "<button class='close fixed' onclick='delArticle(this)'  style='float:right;right:15px;margin-top: 4px;'>&times;</button>";
                        article += "<div class='fl itemTitle'>";
                        article += data.info.title;
                        article += "</div>";
                        article += "<div class = 'fr indexImage'><img src='" + data.info.index + "' /> </div>";
                        article += "</div>";
                    }
                    $('#ArticlePreviewBox').append(article);
                     countNum++;
                    saveData(data);
                }
            }

        // 老IE可能不支持Array.prototype.find
        var arrayFind = function (arr, fn) {
            for (var i = 0; i < arr.length; i++) {
                if (fn(arr[i])) return arr[i];
            }
            return undefined;
        }

        // 拖拽绑定
        var elem = $('#ArticlePreviewBox')
                .sortable({
                    // 拖拽结束后的callback
                    stop: function () {
                        // 从dom找到拖拽结束后的id顺序，然后给data重新排序
                        var oldData = $('#ArticlePreviewBox').data('data');
                        var newData = [];
                        $('.localArticle').each(function (index, elem) {
                            var newItem = arrayFind(oldData, function (x) {
                                return x.id.toString() === elem.id.toString()
                            });
                            newData.push(newItem);
                        });

                        $('#ArticlePreviewBox').data('data', newData);
                    }
                });

        //本地保存时
        $("#saveLocal").click(function(){
            $(this).addClass('disabled').text('保存中…');
            updateAlert('操作已提交，请耐心等待……','alert-warning');
            var articles = JSON.stringify($('#ArticlePreviewBox').data('data'), null, 2);
            var mediaId = $("input[name='media_id']").val();
            $.post("{:U('updateNews')}",
                    {media_id:mediaId,articles:articles},
                    function(re){
                        if(re.status == 1){
                            $("input[name='media_id']").val(re.local_id);
                            showInfo(mediaId);
                            showInfo(re.info+re.local_id,'alert-success');
                        }else{
                            showInfo(re.info);
                        }
                        if(re.url){
                            location.href=re.url;
                        }
                    }
            );

            $("#saveLocal").text('保存完成');
        });

        $("#saveAndUpload").click(function(){
            showInfo('正在开发');
        });

        function delArticle(delBtn,noCount){
            $(delBtn).parent().detach();
            noCount || countNum--;
        }

        //弹出提示信息
        function showInfo(info,c){
            c = c || 'alert-error';
            updateAlert(info,c);
            setTimeout(function(){
                $('#top-alert').find('button').click();
            },1500);
        }

        //导航高亮
        highlight_subnav("{:U('news')}");



    </script>
</block>